package com.hy.example.shared.utils;

import com.hy.example.shared.defs.SharedDefs;
import com.hy.example.shared.defs.SharedDefs;
import com.hy.example.shared.defs.SharedDefs;
import lombok.SneakyThrows;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;


public class SharedRunListener extends SpringUtil {

    protected static final String APPLICATION_SHARED_PROPERTIES_RESOURCE = "/application-shared.properties";

    protected static final String APPLICATION_SHARED_LOCAL_PROPERTIES_RESOURCE = "/application-shared-local.properties";


    public SharedRunListener(SpringApplication application, String[] args) {
        super(application, args);
    }

    @Override
    @SneakyThrows
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext,
                                    ConfigurableEnvironment environment) {
        MutablePropertySources mutablePropertySources = environment.getPropertySources();

        if (!mutablePropertySources.contains(APPLICATION_SHARED_PROPERTIES_RESOURCE)) {
            mutablePropertySources.addLast(readEmbeddedProperties(APPLICATION_SHARED_PROPERTIES_RESOURCE,SharedRunListener.class));
        }

        if (environment.acceptsProfiles(SharedDefs.LOCAL_PROFILE) && !mutablePropertySources.contains(APPLICATION_SHARED_LOCAL_PROPERTIES_RESOURCE)) {
            mutablePropertySources.addBefore(APPLICATION_SHARED_PROPERTIES_RESOURCE, readEmbeddedProperties(APPLICATION_SHARED_LOCAL_PROPERTIES_RESOURCE,SharedRunListener.class));
        }


    }
}
